package me.zingon.doc.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * Created by zhidi on 2018-6-7.
 */
@Component
public class EmailUtil {

    @Autowired
    Executor asyncServiceExecutor;

    @Value("${mail.host}")
    String host;

    @Value("${mail.username}")
    String username;

    @Value("${mail.password}")
    String password;

    @Value("${mail.port}")
    String port;

    JavaMailSenderImpl mailSender =new JavaMailSenderImpl();

    @PostConstruct
    public MailSender mailSender(){
        mailSender.setHost(host);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        Properties mailProperties=new Properties();
        mailProperties.setProperty("mail.smtp.auth","true");
        mailProperties.setProperty("mail.smtp.starttls.enable","true");
        mailProperties.setProperty("mail.smtp.timeout","250000");
        mailProperties.setProperty("mail.smtp.port", port);//设置端口
        mailProperties.setProperty("mail.smtp.socketFactory.port", port);//设置ssl端口
        mailProperties.setProperty("mail.smtp.socketFactory.fallback", "false");
        mailProperties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mailSender.setJavaMailProperties(mailProperties);
        return mailSender;
    }


    private void sendTo(String to, String content, String subject) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    //    private void sendImg(String to,String content,String subject,Resource r) throws MessagingException {
//        MimeMessage message=mailSender.createMimeMessage();
//        MimeMessageHelper helper=new MimeMessageHelper(message,true,"utf-8");
//        helper.setFrom(mail_username);
//        helper.setTo(to);
//        helper.setSubject(subject);
//        if(r!=null) {
//            helper.setText("<html><body><h1>"+ content+"</h1><img src='cid:img'></body></html>", true);
//            helper.addInline("img", r);
//        }else{
//            helper.setText("<html><body>"+content+"</body></html>", true);
//        }
//        mailSender.send(message);
//    }
    public void sendEmail(final String to, final String content, final String subject) {
        asyncServiceExecutor.execute(new Runnable() {
            @Override
            public void run() {
                sendTo(to, content, subject);
            }
        });
    }

}
